<script setup lang="ts">
import { onMounted, ref, onBeforeUnmount, type Ref, nextTick } from 'vue'
import { MdPreview } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import 'md-editor-v3/lib/preview.css';

const isConnected = ref(false);
const userMessage = ref('');
const aiMessage = ref('');
const chatList = ref<ChatListType[]>([]);
const output = ref('');

// 悬浮按钮相关状态
const floatingButton = ref<HTMLElement | null>(null);
const menu = ref<HTMLElement | null>(null);
const isDragging = ref(false);
const offsetX = ref(0);
const offsetY = ref(0);
const buttonPosition = ref({ x: 80, y: 80 }); // 初始位置
const isMenuOpen = ref(false); // 菜单是否打开

// 菜单选项数据
const menuItems = ref([
  { id: 1, label: '教师工作助手', icon: 'fa-home' },
  { id: 2, label: '学生学习助手', icon: 'fa-history' },
  { id: 3, label: '管理控制助手', icon: 'fa-cog' },
]);

let websocket: WebSocket;

//发送问题
function sendMessage(message:string) {
  aiMessage.value = ''
  chatList.value.push({content:message,type:"USER"});
  if (websocket.readyState === WebSocket.OPEN) {
    websocket.send(message);
  } else {
    console.error('WebSocket connection not open.');
  }
  userMessage.value = ''
}


onMounted(() => {
  const url = '/dev-api/websocket/aiChat';
  websocket = new WebSocket(url);
  websocket.onopen = () => {
    isConnected.value = true;
    console.log("Websocket connected success");
  };

  websocket.onmessage = (event) => {
    if (event.data == '\u003cthink\u003e') {
      output.value += "<div style=\"color: #30a1b5\">"
    } else if (event.data == '\u003c/think\u003e') {
      output.value += "</div>"
    }
    else {
      output.value += event.data;
    }

    if (event.data == '\u003cthink\u003e') {
      aiMessage.value += "<div style=\"color: #30a1b5\">"
    } else if (event.data == '\u003c/think\u003e') {
      aiMessage.value += "</div>"
    }
    else {
      aiMessage.value += event.data;
    }

    if (chatList.value.length > 0 && chatList.value[chatList.value.length-1].type === "USER") {
      chatList.value.push({content:aiMessage.value,type:"AI"})
    } else if (chatList.value.length > 0) {
      chatList.value[chatList.value.length - 1].content = aiMessage.value;
    }
  };

  websocket.onclose = () => {
    isConnected.value = false;
    // 服务端连接关闭后的操作
  };

  websocket.onerror = (error) => {
    console.error('WebSocket error:', error);
    // 错误处理
  };

  // 初始化悬浮按钮和菜单
  floatingButton.value = document.getElementById('floating-button');
  menu.value = document.getElementById('floating-menu');

  // 点击页面其他地方关闭菜单
  document.addEventListener('click', handleOutsideClick);
});

onBeforeUnmount(() => {
  if (websocket) {
    websocket.close();
  }

  // 移除全局事件监听
  document.removeEventListener('click', handleOutsideClick);
  window.removeEventListener('mousemove', handleDrag);
  window.removeEventListener('mouseup', endDrag);
});

// 处理点击菜单外部区域
const handleOutsideClick = (e: MouseEvent) => {
  if (!floatingButton.value || !menu.value) return;

  // 如果点击的不是按钮和菜单区域，关闭菜单
  if (!floatingButton.value.contains(e.target as Node) && !menu.value.contains(e.target as Node)) {
    isMenuOpen.value = false;
  }
};

// 切换菜单显示状态
const toggleMenu = (e: MouseEvent) => {
  e.stopPropagation(); // 阻止事件冒泡，避免触发外部点击事件
  isMenuOpen.value = !isMenuOpen.value;
};

// 点击菜单项
const handleMenuItemClick = (item: any) => {
  console.log('Menu item clicked:', item);
  isMenuOpen.value = false;

  // 这里可以添加菜单项点击后的具体逻辑
  switch(item.id) {
    case 1:

      window.location.href = 'https://www.baidu.com';
      break;
    case 2:

      break;
    case 3:

      break;
    case 4:
      // 显示帮助逻辑
      break;
  }
};

// 悬浮按钮拖动相关函数
const startDrag = (e: MouseEvent) => {
  // 如果菜单是打开的，点击按钮先关闭菜单
  if (isMenuOpen.value) {
    isMenuOpen.value = false;
    e.stopPropagation();
  }

  if (!floatingButton.value) return;

  isDragging.value = true;
  const rect = floatingButton.value.getBoundingClientRect();

  // 计算鼠标点击位置与按钮左上角的偏移量
  offsetX.value = e.clientX - rect.left;
  offsetY.value = e.clientY - rect.top;

  // 添加过渡动画
  floatingButton.value.style.transition = 'none';
  floatingButton.value.style.opacity = '0.8';

  // 临时关闭菜单过渡效果，防止拖动时菜单位置异常
  if (menu.value) {
    menu.value.style.transition = 'none';
  }
};

const handleDrag = (e: MouseEvent) => {
  if (!isDragging.value || !floatingButton.value) return;

  // 计算新位置，考虑视口边界
  let newX = e.clientX - offsetX.value;
  let newY = e.clientY - offsetY.value;

  // 确保按钮不会被拖出视口
  const buttonWidth = floatingButton.value.offsetWidth;
  const buttonHeight = floatingButton.value.offsetHeight;

  newX = Math.max(0, Math.min(window.innerWidth - buttonWidth, newX));
  newY = Math.max(0, Math.min(window.innerHeight - buttonHeight, newY));

  // 更新按钮位置
  buttonPosition.value = { x: newX, y: newY };
};

const endDrag = () => {
  if (!isDragging.value || !floatingButton.value) return;

  isDragging.value = false;

  // 添加释放时的动画效果
  floatingButton.value.style.transition = 'all 0.3s ease';
  floatingButton.value.style.opacity = '1';

  // 恢复菜单过渡效果
  if (menu.value) {
    menu.value.style.transition = 'all 0.3s ease';
  }

  // 吸附到最近的侧边
  const buttonWidth = floatingButton.value.offsetWidth;
  const buttonHeight = floatingButton.value.offsetHeight;
  const menuWidth = menu.value ? menu.value.offsetWidth : 180;

  const leftDist = buttonPosition.value.x;
  const rightDist = window.innerWidth - buttonPosition.value.x - buttonWidth;
  const topDist = buttonPosition.value.y;
  const bottomDist = window.innerHeight - buttonPosition.value.y - buttonHeight;

  const minDist = Math.min(leftDist, rightDist, topDist, bottomDist);

  // 根据吸附位置调整菜单显示方向
  if (minDist === leftDist) {
    buttonPosition.value.x = 0;
    // 如果吸附到左侧，菜单显示在右侧
    menu.value?.style.setProperty('--menu-position', 'right');
  } else if (minDist === rightDist) {
    buttonPosition.value.x = window.innerWidth - buttonWidth;
    // 如果吸附到右侧，菜单显示在左侧
    menu.value?.style.setProperty('--menu-position', 'left');
  } else if (minDist === topDist) {
    buttonPosition.value.y = 0;
  } else {
    buttonPosition.value.y = window.innerHeight - buttonHeight;
  }
};

// 全局监听鼠标移动和释放事件
window.addEventListener('mousemove', handleDrag);
window.addEventListener('mouseup', endDrag);

type ChatListType =  {
  content: string,
  type: string,
}
</script>

<template>
  <div class="container">
    <div class="panel-container">

      <div v-if="chatList.length > 0" class="panel-body">
        <div class="panel" v-for="(item, index) in chatList">
          <div class="user_right" v-if="item.type === 'USER'">
            <el-text class="my-text">
              {{item.content}}
            </el-text>
          </div>
          <div class="ai_left" v-else>
            <MdPreview class="my_md_preview" :modelValue="item.content" previewTheme="cyanosis"></MdPreview>
          </div>
        </div>
      </div>
      <div class="sy">
        <!-- 视频作为背景 -->
        <video autoplay muted playsinline loop>
          <source src="/src/assets/img/77.mp4" type="video/mp4" />
        </video>

        <!-- 盒子内容 -->
<!--        <div class="content">-->
<!--          <h3>视频背景示例</h3>-->
<!--          <p>这段内容显示在视频背景之上</p>-->
<!--        </div>-->
      </div>
      <div :class="chatList.length > 0 ? 'user_padding_bottom' : 'user_padding'">

        <el-input @keydown.enter="sendMessage(userMessage)" v-model="userMessage" type="text" class="user_input" placeholder="输入内容..." />
      </div>
    </div>

    <!-- 悬浮按钮 -->
    <div
      id="floating-button"
      class="floating-button"
      :style="{
        left: buttonPosition.x + 'px',
        top: buttonPosition.y + 'px'
      }"
      @mousedown="startDrag"
      @click="toggleMenu"
    >
      <i class="fa fa-bars"></i>
    </div>

    <!-- 悬浮菜单 -->
    <div
      id="floating-menu"
      class="floating-menu"
      :style="{
        left: buttonPosition.x + (menuPosition === 'right' ? 70 : -190) + 'px',
        top: buttonPosition.y + 'px',
        opacity: isMenuOpen ? '1' : '0',
        visibility: isMenuOpen ? 'visible' : 'hidden',
        transform: isMenuOpen ? 'translateY(0)' : 'translateY(10px)'
      }"
    >
      <ul class="menu-items">
        <li
          v-for="item in menuItems"
          :key="item.id"
          class="menu-item"
          @click="handleMenuItemClick(item)"
        >
          <i :class="['fa', item.icon]"></i>
          <span>{{item.label}}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped>
.container {
  height: 100vh;
  max-width: 2560px;
  background-size: cover;
  background-image: url("/src/assets/img/banner-background.webp");
  background-position: center;
  position: relative;
  background-color: rgba(255, 255, 255, 0.5);
}

.container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.2);
}

.panel-container {
  height: 100vh;
  position: relative;
  overflow: hidden;
}

.panel-body {
  width: 70vw;
  height: 100%;
  padding-bottom: 120px;
  overflow-y: auto;
  margin: 0 auto;
}

.user_padding {
  position: fixed;
  top: 60%;
  left: 50%;
  transform: translateX(-50%);
  border-radius: 20px;
  background-color: #ffffff;
}

.user_padding_bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  box-shadow: 0 -2px 4px rgba(0,0,0,0.05);
}

.user_input {
  position: fixed;
  bottom: 20px;
  padding: 0 12px;
  left: 50%;
  transform: translateX(-50%);
  max-height: 150px;
  width: 70vw;
  height: 80px;
  font-size: 20px;
  border-radius: 20px;
  background-color: rgba(44, 133, 182, 0.5);
  border: #f3f4f6 solid 1px;
}

.panel {
  margin: 50px 0 10px 0;
}

.user_right {
  display: flex;
  justify-content: flex-end;
}

.ai_left {
  display: inline-block;
  justify-content: flex-start;
  overflow: hidden;
  border-radius: 20px;
}

.my-text {
  padding: 10px 15px 10px 15px;
  border-radius: 15px;
  background-color: rgba(148, 248, 214, 0.3);
}

.my_md_preview {
  background-color: rgba(252, 227, 138, 0.2);
}

:deep(.md-editor-preview) {
  margin-top: 0;
  padding: 10px 20px;
}

:deep([data-v-db8eed24] div.cyanosis-theme p) {
  line-height: inherit;
  margin-top: 0;
}

:deep(div.cyanosis-theme p) {
  line-height: inherit;
}

.panel-body::-webkit-scrollbar {
  display: none;
}

/* 悬浮按钮样式 */
.floating-button {
  position: fixed;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  /*background-color: #2c85b6;*/
  background-image: url(src/assets/img/2.png);
  background-position: center; /* 背景图片居中 */
  background-repeat: no-repeat; /* 背景图片不重复 */
  background-size: contain; /* 保持图片比例，最大尺寸显示 */
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  z-index: 999;
  transition: all 0.3s ease;
  font-size: 24px;
}

.floating-button:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.floating-button:active {
  transform: scale(0.98);
}

/* 悬浮菜单样式 */
.floating-menu {
  position: fixed;
  width: 180px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  z-index: 998;
  transition: all 0.3s ease;
  opacity: 0;
  visibility: hidden;
  transform: translateY(10px);
}

.menu-items {
  list-style: none;
  padding: 8px 0;
  margin: 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

.menu-item i {
  width: 24px;
  margin-right: 12px;
  color: #2c85b6;
}

.menu-item span {
  color: #333;
  font-size: 14px;
}
/*.sy{
  width: 100px;
  height: 100px;
  background-color: #2c85b6;
  margin: 100px auto;
  !*overflow: hidden; !* 隐藏超出部分 *!*!
}
.sy video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover; !* 保持视频比例并覆盖容器 *!
  z-index: -1; !* 置于底层 *!
}*/
.sy {
  position: relative; /* 添加相对定位 */
  width: 100px;       /* 增加宽度以便查看效果 */
  height: 100px;
  background-color: #2c85b6;
  margin: 100px auto;
  border-radius: 50px;
  overflow: hidden;   /* 确保视频不会溢出容器 */
}

.sy video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: 0;         /* 调整z-index，使视频位于内容下方 */
}

.sy .content {
  position: relative;
  z-index: 1;         /* 确保内容显示在视频上方 */
  padding: 20px;
  color: white;       /* 设置文本颜色以便查看 */
  background-color: rgba(0,0,0,0.3); /* 添加半透明背景增强可读性 */
}
</style>